﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;

namespace AWS.SLAM.Hierarchy
{
    public static class InstallationValidator
    {
        private static string _slamFeatureId = "7a5c5b0e-9ede-4cfe-b72d-2b84a4ddef5f";
        private static string _slamAssemblyName = "AWS.SLAM, Version=*.*.*.*, Culture=neutral, PublicKeyToken=28f8d30936a98765";

        public static void ActivateSlamFeature()
        {
            SPSite site = SPControl.GetContextSite(HttpContext.Current);
            site.Features.Add(new Guid(_slamFeatureId));
        }

        public static bool VerifySlamEventsAreAttached(SPList list)
        {
            bool eventsAttached = false;
            foreach (SPEventReceiverDefinition receiver in list.EventReceivers)
            {
                if ((receiver.Assembly.StartsWith(_slamAssemblyName.Substring(0, _slamAssemblyName.IndexOf(",") + 1)) &&
                    receiver.Assembly.EndsWith(_slamAssemblyName.Substring(_slamAssemblyName.LastIndexOf(",") + 1))) ||
                    receiver.Name.StartsWith("SLAM"))
                {
                    eventsAttached = true;
                    break;
                }
            }
            return eventsAttached;
        }

        public static bool VerifySlamIsActivated()
        {
            bool slamActivated = false;
            SPSite site = SPControl.GetContextSite(HttpContext.Current);
            foreach (SPFeature feature in site.Features)
            {
                if (feature.Definition != null && feature.Definition.Id != null && feature.Definition.Id.ToString().ToLower() == _slamFeatureId)
                {
                    slamActivated = true;
                    break;
                }
            }

            return slamActivated;
        }

        public static bool VerifySlamIsInstalled()
        {
            bool slamInstalled = false;
            foreach (SPFeatureDefinition feature in SPFarm.Local.FeatureDefinitions) 
            {
                if (feature.Id.ToString().ToLower() == _slamFeatureId)
                {
                    slamInstalled = true;
                    break;
                }
            }

            return slamInstalled;
        }
    }
}
